<?php

include dirname(dirname(dirname(__FILE__))) . '/include/common.php';

class webServiceUpdateBudgetGoal extends core {

    public function process() {
        $total_budget = preg_replace('/[^0-9\.]/', '', $_POST['total_budget']);
        $total_budget = floatval($total_budget);
        $user_id = intval($_POST['user_id']);
        $result_spent = $this->db->get_row("SELECT SUM(item_amount) AS total_spent FROM budget_items,users WHERE user_id=$user_id AND budget_items.user_id = users.id");
        if ($result_spent) {
            $money_spent = $result_spent->total_spent;
        } else {
            $this->_JSONResponse(array('error' => 1, 'msg' => "Oops, something went wrong. Please try again."));
        }
        $query = "UPDATE `users` SET `budget_goal`=" . $total_budget . " WHERE `id`= $user_id";

        if ($this->db->query($query) === false) {

            $this->_JSONResponse(array('error' => 1, 'msg' => 'Oops, something went wrong. Please try again'));
        } else {
            $unused_money = $total_budget - $money_spent;
            $format_unused_money = strval(number_format($unused_money, 2));
            $length = strlen($format_unused_money);
            $str_int_unused_money = strval(intval($unused_money));
            $html_unused_money = '';
            if (strlen($str_int_unused_money) % 3 == 0) {
                $html_unused_money .='<span class="wd-number-item">0</span>';
            }

            for ($i = 0; $i < $length; $i++) {
                if ($format_unused_money[$i] == ",") {
                    $html_unused_money.='<span class="wd-number-item-space">,</span>';
                } elseif ($format_unused_money[$i] == ".") {
                    $html_unused_money.='<span class="wd-number-item-dot">.</span>';
                } else {
                    $html_unused_money.='<span class="wd-number-item">' . $format_unused_money[$i] . '</span>';
                }
            }
            $this->_JSONResponse(array('error' => 0, 'msg' => 'Budget goal has been updated',
                'unused_money'=>$html_unused_money,'goal'=>"$ ".number_format($total_budget)));
        }
    }

}

$processor = new webServiceUpdateBudgetGoal();
$processor->process();
?>